<template>
  <div class="verify-code">
    <canvas ref="canvas" @click="refreshCode"></canvas>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';

import api from '../services/api';

const canvas = ref(null);
const code = ref('');

// 绘制验证码到canvas
const drawCode = (str) => {
  const ctx = canvas.value.getContext('2d');
  canvas.value.width = 120;
  canvas.value.height = 40;
  ctx.fillStyle = '#f0f0f0';
  ctx.fillRect(0, 0, canvas.value.width, canvas.value.height);
  ctx.font = 'bold 24px Arial';
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  for (let i = 0; i < str.length; i++) {
    const x = 30 + i * 20;
    const y = 20 + Math.random() * 8 - 4;
    const deg = Math.random() * 30 * Math.PI / 180;
    ctx.fillStyle = `rgb(${Math.random() * 100 + 100}, ${Math.random() * 100 + 100}, ${Math.random() * 100 + 100})`;
    ctx.save();
    ctx.translate(x, y);
    ctx.rotate(deg);
    ctx.fillText(str[i], 0, 0);
    ctx.restore();
  }
  for (let i = 0; i < 4; i++) {
    ctx.strokeStyle = `rgb(${Math.random() * 200 + 50}, ${Math.random() * 200 + 50}, ${Math.random() * 200 + 50})`;
    ctx.beginPath();
    ctx.moveTo(Math.random() * canvas.value.width, Math.random() * canvas.value.height);
    ctx.lineTo(Math.random() * canvas.value.width, Math.random() * canvas.value.height);
    ctx.stroke();
  }
  for (let i = 0; i < 30; i++) {
    ctx.fillStyle = `rgb(${Math.random() * 200 + 50}, ${Math.random() * 200 + 50}, ${Math.random() * 200 + 50})`;
    ctx.beginPath();
    ctx.arc(Math.random() * canvas.value.width, Math.random() * canvas.value.height, 1, 0, 2 * Math.PI);
    ctx.fill();
  }
};

const fetchVerifyCode = async () => {
  try {
    const response = await api.get('/auth/verify-code');
    if (response.data.success) {
      localStorage.setItem('verifySessionId', response.data.sessionId);
      code.value = response.data.code;
      drawCode(code.value);
    }
  } catch (error) {
    console.error('获取验证码失败:', error);
  }
};

const refreshCode = () => {
  fetchVerifyCode();
};

defineExpose({ refreshCode });

onMounted(() => {
  fetchVerifyCode();
});
</script>

<style scoped>
.verify-code {
  display: inline-block;
  cursor: pointer;
}
.verify-code canvas {
  width: 140px !important;
  height: 48px !important;
  vertical-align: middle;
}
</style>